/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trafficando.presentation.controller;

import com.appspot.trafficando.domain.EventAggregator;
import com.appspot.trafficando.domain.EventType;
import java.util.HashSet;
import java.util.Set;
import org.apache.abdera.ext.geo.Coordinate;
import org.apache.abdera.ext.geo.Point;
import org.apache.abdera.model.Feed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ResourceController {

    private EventAggregator aggregator;

    @Autowired
    public void setAggregator(EventAggregator aggregator) {
        this.aggregator = aggregator;
    }

    @RequestMapping("/{eventType}/search")
    public String getNearestEvents(@PathVariable("eventType") String eventType, @RequestParam("lat") String lat, @RequestParam("lng") String lng, @RequestParam("rng") String rng, Model model) {
        final EventType eType = EventType.valueOf(eventType.toUpperCase());
        double latitude = Double.parseDouble(lat);
        double longitude = Double.parseDouble(lng);
        Point p = new Point(new Coordinate(latitude, longitude));
        Integer range = Integer.valueOf(rng) * 1000;
        Set<EventType> eTypes = new HashSet<EventType>(1);
        eTypes.add(eType);
        Feed feed = this.aggregator.getNearestEvents(p, range, eTypes);
        model.addAttribute("lat", latitude);
        model.addAttribute("lng", longitude);
        model.addAttribute("rng", rng);
        model.addAttribute("feed", feed);
        return "searchResult";
    }
}
